# Create your views here.
# -*- coding: utf-8 -*-
from audioop import reverse
from datetime import datetime, date
import string
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, redirect, HttpResponse, RequestContext, get_object_or_404
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf
from pprint import pprint
from Exam.models import *

# Check if user is a teacher
def is_teacher(user):
    return Teacher.objects.all().filter(username=user).count() > 0

@login_required
def index(request):
    request.teacher = is_teacher(request.user)

    return render_to_response('index.html', RequestContext(request))

@login_required
def logout_view(request):
    logout(request)
    return redirect(exam_list)

@login_required
def exam_list(request):
    request.teacher = is_teacher(request.user)


    expired_exams = Exam.objects.all().filter(deadline__lt = date.today())
    if request.teacher:
        comp_exams = allGrades.objects.all()
        open_exams = Exam.objects.all().filter(deadline__gte = date.today())
    else:
        comp_exams = allGrades.objects.all().filter(username = request.user)
        open_exams = Exam.objects.all().filter(deadline__gte = date.today()).exclude(allgrades__in = comp_exams)

    obj = { 'open_exams' : open_exams, 'expired_exams' : expired_exams, 'comp_exams' : comp_exams }

    return render_to_response('exam_list.html', obj, RequestContext(request))

@login_required
def create_exam(request):
    request.teacher = is_teacher(request.user)
    if not request.teacher:
        return HttpResponseRedirect('/exams')

    if request.method == 'GET':
        return render_to_response('create_exam.html', RequestContext(request))
    else:
        form = request.POST
        qL = form.getlist('question')

        tmp_e = Exam(name = form['name'], created = datetime.now(), deadline = form['deadline'], author = request.user)
        tmp_e.save() # Save Exam

        getQ = form.getlist('q')
        getA = form.getlist('a')


        q_counter = 0
        for q_tmp in getQ:
            q_counter += 1

        a_counter = 0
        for a_tmp in getA:
            a_counter += 1

        # Questions cannot be empty
        if q_counter < 1:
            return HttpResponse('Questions can not be empty!')
        # Answers cannot be empty
        if a_counter < 1:
            return HttpResponse('Answers can not be empty!')

        i = 0
        for q in qL:
            tmp_q = ExamQuestion(question = q, exam_id = tmp_e.id)
            tmp_q.save() # Save Question
            aL = form.getlist('answer[' + str(getQ[i]) + ']')
            j = 0
            for a in aL:
                tmp_a = ExamAnswer(answer = a, question_id = tmp_q.id, correctAnswer = form['correct[' + str(getQ[i]) + '][' + str(getA[j]) + ']'])
                tmp_a.save() # Save Answer
                j += 1
            i += 1

        return HttpResponseRedirect('/exams')

@login_required
def view_exam(request, exam_id):
    request.teacher = is_teacher(request.user)
    tmp_e = Exam.objects.get(pk = exam_id)
    uhc = Grades.objects.all().filter(username = request.user, exam__id = exam_id)

    # Teachers can not take exams
    # Student may not have taken the exam
    # Exam deadline can not been reached
    if (request.teacher or uhc.count() > 0) or (tmp_e.deadline < date.today()):
        return HttpResponseRedirect('/exams')

    if request.method == 'GET':
        question = ExamQuestion.objects.filter(exam__id = exam_id)
        q = []

        for quest in question:
            a = []
            answers = ExamAnswer.objects.filter(question__id = quest.id)
            for ans in answers:
                a.append({"Aid" : ans.id, "Aanswer" : ans.answer, "Aquestion_id" : ans.question_id, "AcorrectAnswer" : ans.correctAnswer})

            q.append({"Qid" : quest.id,
                      "Qquestion" : quest.question,
                      "Qexam_id" : quest.exam_id,
                      "Qanswer" : a })

        obj = {"exam_questions" : q}
        return render_to_response('exam_details.html', obj, RequestContext(request))

    else:

        form = UserAnswer(request.POST)
        form1 = form.id

        count = 1
        answ = []
        for a in form1:
            obje = UserAnswer(username = request.user.username, answer_id = form1[str(count)])

            #find out which grades are correct.
            ob = ExamAnswer.objects.get(id = form1[str(count)])
            if ob.correctAnswer == 1:
                answ.append(1)
            else:
                answ.append(0)
                #save the object to the database
            obje.save()
            count += 1

        #calculate grade and save it to the database
        weight = 10.0/(count-1)
        grade = 0
        for a in answ:
            grade += (a * weight)

        obj_grade = Grades(username = request.user, exam_id = exam_id, grade = grade)
        obj_grade.save()


        return HttpResponseRedirect('/grades')


def delete_exam(request, exam_id):
    request.teacher = is_teacher(request.user)
    if not request.teacher:
        return HttpResponseRedirect('/exams')

    g = Grades.objects.all().filter(exam__id = exam_id)
    e = Exam.objects.all().filter(pk = exam_id)
    q = ExamQuestion.objects.all().filter(exam__id = exam_id)
    for qitem in q:
        a = ExamAnswer.objects.all().filter(question__id = qitem.id)
        a.delete()
    g.delete()
    e.delete()
    q.delete()

    return HttpResponseRedirect('/exams')

def calc_grades(request):
    MyGrades = allGrades.objects.filter(username = request.user)

    GradesAndAverage = []
    sum_my_grades = 0
    count_my_grades = 0
    for g in MyGrades:
        gr = Grades.objects.filter(exam__id = g.exam_id).order_by('exam__id')
        count_my_grades += 1
        sum_my_grades += float(g.grade)
        count = 0
        sum = 0.0
        for av in gr:
            sum = sum + float(av.grade)
            count += 1
        aver = (sum/count)

        GradesAndAverage.append({"name" : g.name, "username" : g.username, "grade" : g.grade, "average" : aver})
        my_Grades = sum_my_grades/count_my_grades

    if MyGrades.count() > 0:
        obj = {"all" : GradesAndAverage, "Average_my_grades" : my_Grades, "GradeCount" : MyGrades.count()}
    else:
        obj = {"GradeCount" : MyGrades.count()}


    return  render_to_response('grades.html', obj,  RequestContext(request))
